package com.ybc.chinese.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ybc.chinese.R;
import com.ybc.chinese.adapter.JokeAdapter;
import com.ybc.chinese.bean.Joke;
import com.ybc.chinese.utils.CacheUtil;
import com.ybc.chinese.utils.CommonUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.ybc.chinese.R.string.joke;

/**
 * <p>笑话大全<p/>
 * Created by Yubch on 17/2/20.
 */
public class JokeActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ListView> {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_left)
    ImageView ivLeft;
    @Bind(R.id.lv_joke)
    PullToRefreshListView lvJoke;

    private Context mCtx;
    private String url = "http://v.juhe.cn/joke/randJoke.php";
    private static final String INDEX_JOKE = "index/joke";
    private int mOffset = 0;
    private JokeAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_joke);
        ButterKnife.bind(this);
        mCtx = this;
        initView();
        List<Joke.ResultBean> resultBeen = getCache();
        if(!CommonUtil.isEmpty(resultBeen)) {
            mAdapter.setData(resultBeen, false);
        } else {
            showRunningDialog();
        }
        request();
    }

    private void request() {
        if (!CommonUtil.isNetworkConnected(mCtx)) {
            dismissRunningDialog();
            CommonUtil.showToast(mCtx, R.string.no_net);
            lvJoke.onRefreshComplete();
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("key", "eb36ddf0495f546681db699b8848ccbc");
        builder.add("type", "pic");
        RequestBody formBody = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                CommonUtil.showToast(mCtx, "数据请求失败");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String json = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Joke joke = new Gson().fromJson(json, Joke.class);
                        if (0 == joke.getError_code()) {
                            List<Joke.ResultBean> resultBeen = joke.getResult();
                            if(mOffset == 0) {
                                mAdapter.setData(resultBeen, false);
                                CacheUtil.saveCache(mCtx, INDEX_JOKE, new Gson().toJson(resultBeen));
                            } else {
                                mAdapter.setData(resultBeen, true);
                            }
                        } else {
                            CommonUtil.showToast(mCtx, "数据请求失败");
                        }
                        lvJoke.onRefreshComplete();
                        dismissRunningDialog();
                    }
                });
            }
        });
    }

    private List<Joke.ResultBean> getCache() {
        String jsonResultBeen = CacheUtil.getCache(mCtx, INDEX_JOKE);
        List<Joke.ResultBean> resultBeen = new ArrayList<>();
        if(!TextUtils.isEmpty(jsonResultBeen)) {
            resultBeen = new Gson().fromJson(jsonResultBeen, new TypeToken<List<Joke.ResultBean>>(){}.getType());
        }
        return resultBeen;
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    private void initView() {
        tvTitle.setText(getString(joke));
        ivLeft.setVisibility(View.VISIBLE);
        ivLeft.setImageResource(R.mipmap.ic_back);
        mAdapter = new JokeAdapter(mCtx);
        lvJoke.setAdapter(mAdapter);
        lvJoke.setMode(PullToRefreshBase.Mode.BOTH);
        lvJoke.setOnRefreshListener(this);
    }

    @OnClick(R.id.iv_left)
    public void back() {
        finish();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mOffset = 0;
        request();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        request();
    }
}
